/**
 * 全文优化服务
 * 提供文章质量分析、优化建议、版本生成等功能
 */

import type {
  QualityReport,
  OptimizationSuggestion,
  OptimizationType,
  OptimizedVersion,
  ComparisonData,
} from '@/stores/optimizer.store';

/**
 * 分析请求
 */
interface AnalyzeRequest {
  content: string;
  options?: {
    includeOriginality?: boolean;    // 是否包含原创度检测
    targetAudience?: string;          // 目标读者
  };
}

/**
 * 优化请求
 */
interface OptimizeRequest {
  content: string;
  type: OptimizationType;
  applyAll?: boolean;                 // 是否应用所有建议
  suggestions?: string[];             // 指定要应用的建议ID
}

/**
 * 对比请求
 */
interface CompareRequest {
  original: string;
  optimized: string;
}

/**
 * 全文优化服务类
 */
class ArticleOptimizerService {
  private baseUrl: string;

  constructor() {
    this.baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
  }

  /**
   * 分析文章质量
   */
  async analyzeArticle(content: string, options?: AnalyzeRequest['options']): Promise<QualityReport> {
    console.log('📊 [ArticleOptimizer] Analyzing article...', { length: content.length });

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/analyze`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ content, options } as AnalyzeRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('✅ [ArticleOptimizer] Analysis complete, score:', data.overall_score);

      return this.transformQualityReport(data);
    } catch (error) {
      console.error('❌ [ArticleOptimizer] Analysis failed:', error);
      // 返回Mock数据
      return this.generateMockQualityReport(content);
    }
  }

  /**
   * 优化文章
   */
  async optimizeArticle(content: string, options: Omit<OptimizeRequest, 'content'>): Promise<{
    content: string;
    changes: Array<{ type: string; description: string; position: number }>;
    score: number;
  }> {
    console.log('✨ [ArticleOptimizer] Optimizing article, type:', options.type);

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/optimize`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ content, ...options } as OptimizeRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('✅ [ArticleOptimizer] Optimization complete');

      return {
        content: data.optimized_content,
        changes: data.changes || [],
        score: data.score || 85,
      };
    } catch (error) {
      console.error('❌ [ArticleOptimizer] Optimization failed:', error);
      // 返回Mock数据
      return this.generateMockOptimization(content, options.type);
    }
  }

  /**
   * 应用单个建议
   */
  async applySuggestion(
    content: string,
    suggestion: OptimizationSuggestion
  ): Promise<string> {
    console.log('🔧 [ArticleOptimizer] Applying suggestion:', suggestion.id);

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/apply-suggestion`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content,
          suggestion_id: suggestion.id,
          suggestion_type: suggestion.type,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return data.updated_content;
    } catch (error) {
      console.error('❌ [ArticleOptimizer] Apply suggestion failed:', error);
      // Mock实现：简单替换
      if (suggestion.originalText && suggestion.suggestedText) {
        return content.replace(suggestion.originalText, suggestion.suggestedText);
      }
      return content;
    }
  }

  /**
   * 应用多个建议
   */
  async applyMultipleSuggestions(
    content: string,
    suggestions: OptimizationSuggestion[]
  ): Promise<string> {
    console.log('🔧 [ArticleOptimizer] Applying', suggestions.length, 'suggestions');

    let optimizedContent = content;

    for (const suggestion of suggestions) {
      optimizedContent = await this.applySuggestion(optimizedContent, suggestion);
    }

    return optimizedContent;
  }

  /**
   * 生成多个优化版本
   */
  async generateVersions(content: string): Promise<OptimizedVersion[]> {
    console.log('🎨 [ArticleOptimizer] Generating multiple versions...');

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/generate-versions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ content }),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return data.versions.map((v: any) => this.transformOptimizedVersion(v));
    } catch (error) {
      console.error('❌ [ArticleOptimizer] Version generation failed:', error);
      // 生成Mock版本
      return this.generateMockVersions(content);
    }
  }

  /**
   * 对比两个版本
   */
  async compareVersions(original: string, optimized: string): Promise<ComparisonData> {
    console.log('📊 [ArticleOptimizer] Comparing versions...');

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/compare`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ original, optimized } as CompareRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return this.transformComparisonData(data);
    } catch (error) {
      console.error('❌ [ArticleOptimizer] Comparison failed:', error);
      return this.generateMockComparison(original, optimized);
    }
  }

  /**
   * 导出优化报告
   */
  async exportReport(data: {
    original: string;
    optimized?: string;
    qualityReport: QualityReport;
    comparisonData?: ComparisonData;
  }): Promise<Blob> {
    console.log('📄 [ArticleOptimizer] Exporting report...');

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/export-report`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
        responseType: 'blob' as any,
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      return await response.blob();
    } catch (error) {
      console.error('❌ [ArticleOptimizer] Export failed:', error);
      // 返回Mock PDF
      return new Blob(['Mock PDF Report'], { type: 'application/pdf' });
    }
  }

  /**
   * 转换质量报告格式
   */
  private transformQualityReport(data: any): QualityReport {
    return {
      overallScore: data.overall_score,
      structureScore: data.structure_score,
      coherenceScore: data.coherence_score,
      readabilityScore: data.readability_score,
      originalityScore: data.originality_score,
      seoScore: data.seo_score,
      languageScore: data.language_score,

      strengths: data.strengths || [],
      weaknesses: data.weaknesses || [],
      suggestions: (data.suggestions || []).map((s: any) => this.transformSuggestion(s)),
      issues: (data.issues || []).map((i: any) => this.transformIssue(i)),

      analyzedAt: Date.now(),
    };
  }

  /**
   * 转换建议格式
   */
  private transformSuggestion(data: any): OptimizationSuggestion {
    return {
      id: data.id,
      type: data.type,
      severity: data.severity,
      title: data.title,
      description: data.description,
      position: data.position,
      originalText: data.original_text,
      suggestedText: data.suggested_text,
      impact: data.impact,
      effort: data.effort,
      timestamp: Date.now(),
    };
  }

  /**
   * 转换问题格式
   */
  private transformIssue(data: any): any {
    return {
      id: data.id,
      type: data.type,
      severity: data.severity,
      position: data.position,
      length: data.length,
      description: data.description,
      suggestion: data.suggestion,
    };
  }

  /**
   * 转换优化版本格式
   */
  private transformOptimizedVersion(data: any): OptimizedVersion {
    return {
      id: data.id,
      type: data.type,
      title: data.title,
      content: data.content,
      score: data.score,
      changes: data.changes || [],
      createdAt: Date.now(),
    };
  }

  /**
   * 转换对比数据格式
   */
  private transformComparisonData(data: any): ComparisonData {
    return {
      original: data.original,
      optimized: data.optimized,
      improvements: data.improvements || [],
      degradations: data.degradations || [],
    };
  }

  /**
   * 生成Mock质量报告
   */
  private generateMockQualityReport(content: string): QualityReport {
    const wordCount = content.length;
    const hasGoodStructure = content.includes('\n\n');

    return {
      overallScore: 75 + Math.floor(Math.random() * 15),
      structureScore: hasGoodStructure ? 85 : 70,
      coherenceScore: 78,
      readabilityScore: wordCount > 500 ? 72 : 80,
      originalityScore: 92,
      seoScore: 68,
      languageScore: 82,

      strengths: [
        '文章结构清晰，层次分明',
        '语言表达流畅，易于理解',
        '内容原创性高，观点独特',
      ],

      weaknesses: [
        'SEO关键词布局需要优化',
        '部分段落过长，影响阅读体验',
        '缺少数据和案例支撑',
      ],

      suggestions: [
        {
          id: `sug_${Date.now()}_1`,
          type: 'title',
          severity: 'high',
          title: '优化标题以提升吸引力',
          description: '当前标题过于简单，建议添加关键词并突出价值主张',
          impact: '预计可提升点击率15-20%',
          effort: 'low',
          timestamp: Date.now(),
        },
        {
          id: `sug_${Date.now()}_2`,
          type: 'opening',
          severity: 'medium',
          title: '改进开头以吸引读者',
          description: '建议在开头添加引人入胜的故事或数据',
          impact: '预计可降低跳出率10%',
          effort: 'medium',
          timestamp: Date.now(),
        },
      ],

      issues: [],
      analyzedAt: Date.now(),
    };
  }

  /**
   * 生成Mock优化结果
   */
  private generateMockOptimization(content: string, type: OptimizationType): {
    content: string;
    changes: Array<{ type: string; description: string; position: number }>;
    score: number;
  } {
    const typeLabels = {
      seo: 'SEO优化',
      readability: '可读性优化',
      professional: '专业深度优化',
      balanced: '平衡优化',
    };

    return {
      content: `[${typeLabels[type]}]\n\n${content}\n\n【优化说明】本版本已根据${typeLabels[type]}策略进行优化。`,
      changes: [
        { type: 'title', description: '优化标题关键词', position: 0 },
        { type: 'structure', description: '调整段落结构', position: 100 },
      ],
      score: 85 + Math.random() * 10,
    };
  }

  /**
   * 生成Mock版本
   */
  private generateMockVersions(content: string): OptimizedVersion[] {
    return [
      {
        id: `v_seo_${Date.now()}`,
        type: 'seo',
        title: 'SEO优化版',
        content: `[SEO优化]\n\n${content}`,
        score: 88,
        changes: [],
        createdAt: Date.now(),
      },
      {
        id: `v_readability_${Date.now()}`,
        type: 'readability',
        title: '可读性优化版',
        content: `[可读性优化]\n\n${content}`,
        score: 86,
        changes: [],
        createdAt: Date.now() + 1,
      },
      {
        id: `v_professional_${Date.now()}`,
        type: 'professional',
        title: '专业深度版',
        content: `[专业深度优化]\n\n${content}`,
        score: 90,
        changes: [],
        createdAt: Date.now() + 2,
      },
    ];
  }

  /**
   * 生成Mock对比数据
   */
  private generateMockComparison(original: string, optimized: string): ComparisonData {
    return {
      original: {
        score: 72,
        wordCount: original.length,
        readabilityScore: 65,
        seoScore: 58,
      },
      optimized: {
        score: 88,
        wordCount: optimized.length,
        readabilityScore: 82,
        seoScore: 76,
      },
      improvements: [
        '整体评分提升16分',
        '可读性提升17分',
        'SEO评分提升18分',
        '添加了5个关键词',
        '优化了标题结构',
      ],
      degradations: [],
    };
  }
}

export const articleOptimizerService = new ArticleOptimizerService();
